//
//  VerificationCodeViewController.m
//  XPhoto
//
//  Created by baboy on 2019/8/5.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "VerificationCodeViewController.h"
#import "BKIndicator.h"
#import "User.h"

@interface VerificationCodeViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) NSArray *textFields;
@property(nonatomic, assign) NSInteger countDownSeconds;
@property(nonatomic, strong) NSTimer *countDownTimer;
@end

@implementation VerificationCodeViewController
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]){
    }
    return self;
}
- (void)createTextFields{
    if (!_textFields) {
        NSMutableArray *arr = [NSMutableArray array];
        NSInteger VCODE_LEN = 6;
        float MARGIN = 10;
        CGFloat fieldWidth = (self.textFieldWrapperView.bounds.size.width - (VCODE_LEN - 1)*MARGIN)/VCODE_LEN;
        CGRect fieldFrame = CGRectMake(0, 0, fieldWidth, fieldWidth);
        
        for (NSInteger i = 0; i < 6; i++) {
            fieldFrame.origin.x = (fieldWidth + MARGIN) * i;
            
            UIView *view = [[UIView alloc] initWithFrame:fieldFrame];
            view.layer.borderColor = [UIColor colorWithWhite:0.9 alpha:1.0f].CGColor;
            view.layer.borderWidth = 1;
            view.backgroundColor = [UIColor whiteColor];
            UITextField *field = [[UITextField alloc] initWithFrame:view.bounds];
            field.font = [UIFont boldSystemFontOfSize:16];
            field.keyboardType = UIKeyboardTypeNumberPad;
            field.textAlignment = NSTextAlignmentCenter;
            field.delegate = self;
            [view addSubview:field];
            [self.textFieldWrapperView addSubview:view];
            [arr addObject:field];
        }
        _textFields = arr;
        [self.textFields.firstObject becomeFirstResponder];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.descLabel.text = [NSString stringWithFormat:@"验证码正在发送到手机 %@", self.mobile];
    [self startCountDown];
    // Do any additional setup after loading the view from its nib.
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self createTextFields];
}
- (void)setCountDownSeconds:(NSInteger)countDownSeconds{
    _countDownSeconds = countDownSeconds;
    NSString *text = [NSString stringWithFormat:@"%lds", countDownSeconds];
    self.countDownLabel.text = text;
    if (countDownSeconds <= 0) {
        [self stopCountDown];
    }
}
- (IBAction) sendSmsCode:( UIButton* _Nullable ) button{
    [self.delegate verificationCodeViewControllerWillResendVCode:self];
    [self startCountDown];
}

- (void)startCountDown{
    self.countDownSeconds = 60;
    self.descLabel.text = [NSString stringWithFormat:NSLocalizedString(@"vcode_send_to_mobile_format", @"提示"), self.mobile];
    if (self.countDownTimer) {
        [self.countDownTimer invalidate];
        self.countDownTimer = nil;
    }
    self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f repeats:YES block:^(NSTimer * _Nonnull timer) {
        self.countDownSeconds --;
    }];
    //
    self.countDownLabel.hidden = NO;
    self.resendButton.hidden = YES;
}
- (void)stopCountDown{
    if (self.countDownTimer) {
        [self.countDownTimer invalidate];
        self.countDownTimer = nil;
    }
    self.countDownLabel.hidden = YES;
    self.resendButton.hidden = NO;
}
- (void)bind{
    NSString *vcode = @"";
    for(NSInteger i = 0, n = self.textFields.count; i < n; i ++){
        UITextField *field = [self.textFields objectAtIndex:i];
        vcode = [NSString stringWithFormat:@"%@%@", vcode,field.text?:field.text];
    }
    [self.delegate verificationCodeViewController:self didInputVCode:vcode];
}

#pragma UITextField delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    DLOG(@"textFiled:%@，%@",textField.text, string);
    int j = -1;
    for(NSInteger i = 0, n = self.textFields.count; i < n; i ++){
        UITextField *field = [self.textFields objectAtIndex:i];
        if(textField == field){
            j = 0;
            if (!string || [string length] == 0) {
                textField.text = string;
                NSInteger k = i - 1;
                while (k >= 0) {
                    UITextField *nextField = [self.textFields objectAtIndex:k] ;
                    if (nextField.text && nextField.text.length > 0) {
                        [nextField becomeFirstResponder];
                        break;
                    }
                    k--;
                }
                break;
            }
        }
        if (j >= 0) {
            if ([string length] > j) {
                textField.text = [string substringWithRange:NSMakeRange(j, 1)];
                j ++;
                if ( (i+1) < n) {
                    UITextField *nextField = [self.textFields objectAtIndex:i+1] ;
                    [nextField becomeFirstResponder];
                }
                if ( (i+1) == n ) {
                    [textField resignFirstResponder];
                    [self bind];
                }
            }
        }
    }
    return NO;
}
//- (void)textFieldDidEndEditing:(UITextField *)textField{
//    for(NSInteger i = 0, n = self.textFields.count; i < n; i ++){
//        UITextField *field = [self.textFields objectAtIndex:i];
//        if(textField == field){
//            if (textField.text.length > 0) {
//                if ( (i+1) >= n ) {
//                    [self send];
//                    return;
//                }
//                UITextField *nextField = [self.textFields objectAtIndex:i+1];
//                [nextField becomeFirstResponder];
//            }
//        }
//    }
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
